package com.top.jwtdemo.interceptor;

import com.top.jwtdemo.annotation.Auth;
import com.top.jwtdemo.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Cjj
 * @data 2024/6/17 11:07
 * @blog blog.jwt.拦截器
 */

/**HandlerInterceptor:自定义拦截器**/
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handlder) throws Exception {
        //instanceof:判断一个对象是否属于某个指定的类或其子类的实例 返回boolean类型
        if (handlder instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handlder;
            //BasicErrorController:用于对异常进行统一处理
            //handlerMethod：处理请求,来获取bean实例 是否 是异常
            if (handlerMethod.getBean() instanceof BasicErrorController) {
                return true;
            }
            //获取Auth注解
            Auth auth = handlerMethod.getMethod().getAnnotation(Auth.class);
            //当auth注解不为空并且auth为true时
            if (auth != null && auth.required()) {
                //通过请求头获取token
                String token = request.getHeader("token");
                //token不能为空
                if (StringUtils.isNoneBlank(token)) {
                    //校验 token
                    if (TokenUtil.verifyToken(token)) {
                        return true;
                    } else {
                        //通过requestDispatcher请求/error/token 发送到重定向
                        request.getRequestDispatcher("/error/tokenError").forward(request, response);
                    }
                } else {
                    //通过requestDispatcher请求/error/token 发送到重定向
                    request.getRequestDispatcher("/error/token").forward(request, response);
                }
            } else {
                return true;
            }
            //放行
        } else {
            return true;
        }
        return false;
    }
}
